//
//  ClassMemberViewController.m
//  家校互通
//
//  Created by 李赛 on 15/7/8.
//  Copyright (c) 2015年 姬鑫宇. All rights reserved.
//

#import "ClassMemberViewController.h"
#import "ClassMenberTableViewCell.h"
#import "TalkModel.h"

@interface ClassMemberViewController ()<ConnectControlDelegate>{
    ConnectControl *connectCtr;
    
}

@property (nonatomic, retain) NSArray *classUserArray;
@property (nonatomic, strong) UIAlertView *customAlertView;
@property (nonatomic, strong) NSMutableArray *classUserArrayIds;
@property (nonatomic, strong) NSMutableString *userIds;
@end

@implementation ClassMemberViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _classUserArrayIds=[[NSMutableArray alloc]initWithCapacity:0];
    _contentTableView.backgroundColor=[UIColor clearColor];
    _contentTableView.delegate=self;
    _contentTableView.dataSource=self;
    //    _contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _contentTableView.allowsMultipleSelectionDuringEditing=YES;
    _contentTableView.tintColor =COLOR(50, 150, 150);   //选中对号为红色
//    // Do any additional setup after loading the view.
    [_contentTableView setEditing:YES animated:YES];
    
    UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [button setTitle:@"确定" forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(sendMsgForCreateClassMateBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:button];
    
    
    connectCtr = [ConnectControl showForView:self.view];
    connectCtr.delegate=self;
    
    if (connectCtr.superview!=nil && connectCtr.loading==NO)
    {
        [connectCtr setLoading:YES];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == alertView.firstOtherButtonIndex) {
        UITextField *nameField = [alertView textFieldAtIndex:0];
//        UITextField *urlField = [alertView textFieldAtIndex:1];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [TalkModel createClazzChart:^(BOOL result, TalkRoomModel *roomList, NSError *error) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            if (result) {
                UUChatViewController *vc =[self.storyboard instantiateViewControllerWithIdentifier:@"UUChatViewController"];
                vc.chartId = roomList.id;
                vc.title = roomList.title;
                AppDelegate *_appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                [_appDelegate.mainViewController.navigationController pushViewController:vc animated:YES];
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"创建聊天室失败，请重试"
                                                                message:nil
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
            
            
        } withToken:[DSFUserInfo shareUserInstance].token andName:nameField.text andClassId:[DSFUserInfo shareUserInstance].clazz_user.clazz.id andUserId:_userIds];
        //TODO
    }
}
-(void)sendMsgForCreateClassMateBtnAction:(UIButton *)sender
{

   _userIds=[NSMutableString stringWithCapacity:0];

    //手动选择的IDs  相当于添加
    [_classUserArrayIds enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        OtherClassModel *channelModel=(OtherClassModel*)obj;
        if (idx==0)
        {
            [_userIds appendString:[NSString stringWithFormat:@"%@",@(channelModel.id)]];
        }
        else
        {
            [_userIds appendString:[NSString stringWithFormat:@",%@",@(channelModel.id)]];
        }
        
    }];
    
    /**
     *  来自聊天室成员添加页面
     */
    if (_chartId>0)
    {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [TalkModel inviteJoinChart:^(BOOL result, TalkRoomModel *roomList, NSError *error) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            if (result) {
                [self.navigationController popViewControllerAnimated:YES];
            }
        } withToken:[DSFUserInfo shareUserInstance].token andChartId:_chartId andUserIds:_userIds];
    
    }
    else
    {
    
        if (_customAlertView==nil) {
            _customAlertView = [[UIAlertView alloc] initWithTitle:@"请输入你创建的群名" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        }
        [_customAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
        
        UITextField *nameField = [_customAlertView textFieldAtIndex:0];
        nameField.placeholder = @"请输入一个群名称";
        [_customAlertView show];
    }

    
//    UITextField *urlField = [_customAlertView textFieldAtIndex:1];
//    [urlField setSecureTextEntry:NO];
//    urlField.placeholder = @"请输入一个URL";
//    urlField.text = @"http://";
 

    

}
- (void)connect
{
    if (_chartId&&![DSFUserInfo shareUserInstance].isTeachLogin)//家长登录，从聊天室进
    {
        [DSFUserInfo getMyFamilyMembers:^(BOOL result, NSString *failMessage, NSArray *familyMembers, NSError *error) {
            [ConnectControl removeFromView:self.view];
            _classUserArray = [NSArray arrayWithArray:familyMembers];
            [_contentTableView reloadData];
        } withToken:[DSFUserInfo shareUserInstance].token andClazzId:[DSFUserInfo shareUserInstance].clazz_user.clazz.id];
    }else
    {
      [DSFUserInfo getClazzUsers:^(BOOL result, NSArray *classUserArr, NSError *error) {
        [ConnectControl removeFromView:self.view];
        _classUserArray = [NSArray arrayWithArray:classUserArr];
        [_contentTableView reloadData];
      } withToken:[DSFUserInfo shareUserInstance].token andClazzId:[DSFUserInfo shareUserInstance].clazz_user.clazz.id];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

#pragma mark UITableViewDelegate--
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_contentTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
  OtherClassModel *model = [_classUserArray objectAtIndex:indexPath.row];
    [_classUserArrayIds addObject:model];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_contentTableView deselectRowAtIndexPath:indexPath animated:YES];
    OtherClassModel *model = [_classUserArray objectAtIndex:indexPath.row];
    [_classUserArrayIds removeObject:model];
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//单元格返回的编辑风格，包括删除 添加 和 默认  和不可编辑三种风格
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}
-(BOOL)hasSelectMemberWithId:(NSInteger)memberId
{
    for ( ChartUser *model in _hasSelectedMember) {
        if (model.id==memberId) {
            return YES;
            break;
        }
    }
    return NO;
}
#pragma mark UITableViewDateSource--
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OtherClassModel *model = [_classUserArray objectAtIndex:indexPath.row];
    ClassMenberTableViewCell *vCell=[tableView dequeueReusableCellWithIdentifier:@"ClassMenberTableViewCell" forIndexPath:indexPath];
    
    if ([self hasSelectMemberWithId:model.id]) {
        [_contentTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        vCell.selectionStyle=UITableViewCellSelectionStyleNone;
     
    }else
    {
        vCell.selectionStyle=UITableViewCellSelectionStyleDefault;
    
    }
    //去除选中时的背景颜色
    UIView *selectView=[[UIView alloc]initWithFrame:vCell.frame];
    selectView.backgroundColor=[UIColor clearColor];
    vCell.multipleSelectionBackgroundView=selectView;
    
    [vCell setContentOfOtherClassUser:model];
    
    return vCell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_classUserArray count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return UIInterfaceOrientationIsPortrait(interfaceOrientation);
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
    
}

-(BOOL)shouldAutorotate
{
    return NO;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
